package com.boruan.shengtangfeng.core.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ClientException;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.green.model.v20180509.ImageSyncScanRequest;
import com.aliyuncs.green.model.v20180509.VideoAsyncScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.boruan.shengtangfeng.core.dao.IVideoDao;
import com.boruan.shengtangfeng.core.entity.Video;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.rmi.ServerException;
import java.util.*;

@Component
public class ALiYunUtils {

    @Autowired
    private IVideoDao videoDao;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String secretAccessKey;
    @Value("${system.baseUrl}")
    private String baseUrl;

    /**
     * 图片鉴黄同步
     * true为不是 false为是
     * @param imageUrl
     * @throws Exception
     */
    public Boolean aliyunImageSyncCheck(String imageUrl) {

        //请替换成你自己的accessKeyId、accessKeySecret
        //IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", "LTAI5tEGVwBDyqYJJaxVZuzn", "5agGnsErmsK1qNQoCmTrQ4Imspgwf8");
        IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKeyId, secretAccessKey);
        IAcsClient client = new DefaultAcsClient(profile);

        ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
        imageSyncScanRequest.setAcceptFormat(FormatType.JSON); // 指定api返回格式
        imageSyncScanRequest.setMethod(com.aliyuncs.http.MethodType.POST); // 指定请求方法
        imageSyncScanRequest.setEncoding("utf-8");
        imageSyncScanRequest.setRegionId("cn-shanghai");
        JSONObject httpBody = new JSONObject();
        /**
         * 设置要检测的风险场景。计费依据此处传递的场景计算。
         * 一次请求中可以同时检测多张图片，每张图片可以同时检测多个风险场景，计费按照场景计算。
         * 例如，检测2张图片，场景传递porn和terrorism，计费会按照2张图片鉴黄，2张图片暴恐检测计算。
         * porn：表示鉴黄场景。
         */
        httpBody.put("scenes", Arrays.asList("porn"));

        /**
         * 设置待检测图片。一张图片对应一个task。
         * 多张图片同时检测时，处理的时间由最后一个处理完的图片决定。
         * 通常情况下批量检测的平均响应时间比单张检测的要长。一次批量提交的图片数越多，响应时间被拉长的概率越高。
         * 这里以单张图片检测作为示例, 如果是批量图片检测，请自行构建多个task。
         */
        JSONObject task = new JSONObject();
        task.put("dataId", UUID.randomUUID().toString());

        // 设置图片链接。
        task.put("url", imageUrl);
        task.put("time", new Date());
        httpBody.put("tasks", Arrays.asList(task));
        /**
         * 请务必设置超时时间
         */
        imageSyncScanRequest.setConnectTimeout(3000);
        imageSyncScanRequest.setReadTimeout(10000);
        boolean flag = false;
        try {
            imageSyncScanRequest.setHttpContent(httpBody.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
            HttpResponse httpResponse = client.doAction(imageSyncScanRequest);

            if (httpResponse.isSuccess()) {
                JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
                //System.out.println(JSON.toJSONString(scrResponse, true));
                if (200 == scrResponse.getInteger("code")) {
                    JSONArray taskResults = scrResponse.getJSONArray("data");
                    for (Object taskResult : taskResults) {
                        if (200 == ((JSONObject) taskResult).getInteger("code")) {
                            JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
                            for (Object sceneResult : sceneResults) {
                                String scene = ((JSONObject) sceneResult).getString("scene");
                                String suggestion = ((JSONObject) sceneResult).getString("suggestion");
                                //根据scene和suggetion做相关的处理
                                //do something
                                System.out.println("scene = [" + scene + "]");
                                System.out.println("suggestion = [" + suggestion + "]");
                                if (!"pass".equals(suggestion)) {
                                    flag = false;
                                    return flag;
                                } else {
                                    flag = true;
                                }
                            }
                        } else {
                            System.out.println("task process fail:" + ((JSONObject) taskResult).getInteger("code"));
                            //return GlobalReponse.fail(scrResponse);
                        }
                    }
                } else {
                    System.out.println("detect not success. code:" + scrResponse.getInteger("code"));
                    //return GlobalReponse.fail(scrResponse);
                }
            } else {
                System.out.println("response not success. status:" + httpResponse.getStatus());
                //return GlobalReponse.fail("response not success. status:" + httpResponse.getStatus());
            }
        } catch (ClientException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     *视频鉴黄异步
     * @param videoUrl
     * @return
     */
    public void aliyunVideoSyncCheck(String videoUrl,Long videoId) {
        try {
            IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKeyId, secretAccessKey);
            DefaultProfile.addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
            IAcsClient client = new DefaultAcsClient(profile);

            VideoAsyncScanRequest videoAsyncScanRequest = new VideoAsyncScanRequest();
            videoAsyncScanRequest.setAcceptFormat(FormatType.JSON); // 指定API返回格式。
            videoAsyncScanRequest.setMethod(com.aliyuncs.http.MethodType.POST); // 指定请求方法。

            List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();
            Map<String, Object> task = new LinkedHashMap<String, Object>();
            task.put("dataId", UUID.randomUUID().toString());
            task.put("url", videoUrl);
            task.put("interval",3);
            tasks.add(task);
            /**
             * 设置要检测的场景。计费是依据此处传递的场景计算。
             * 视频默认1秒截取一帧，您可以自行控制截帧频率。收费按照视频的截帧数量以及每一帧的检测场景计算。
             * 举例：1分钟的视频截帧60张，检测色情（对应场景参数porn）和暴恐涉政（对应场景参数terrorism）2个场景，收费按照60张色情+60张暴恐涉政进行计费。
             */
            JSONObject data = new JSONObject();
            data.put("scenes", Arrays.asList("porn"));
            data.put("tasks", tasks);
            data.put("callback", baseUrl+"/aliyun/oss/aliYunVideoAuditReturn");
            data.put("seed", "cb23Jq2eWL4Uf7c5S2hTXeUQ-1uU48A");

            videoAsyncScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
            /** 请务必设置超时时间。*/
            videoAsyncScanRequest.setConnectTimeout(3000);
            videoAsyncScanRequest.setReadTimeout(6000);
            HttpResponse httpResponse = client.doAction(videoAsyncScanRequest);
            if (httpResponse.isSuccess()) {
                JSONObject jsonObject = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
                String msg = jsonObject.getString("msg");
                String code = jsonObject.getString("code");
                if (msg.equals("OK") && code.equals("200")){
                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                    JSONObject jsonObject0 = jsonArray.getJSONObject(0);
                    String taskId = jsonObject0.getString("taskId");
                    Video video = videoDao.unique(videoId);
                    video.setTaskId(taskId);
                    videoDao.updateTemplateById(video);
                }
                System.out.println(JSON.toJSONString(jsonObject, true));
            } else {
                System.out.println("response not success. status:" + httpResponse.getStatus());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}




